#!/usr/bin/python
import subprocess,os,re,datetime,sys,linecache,codecs,chardet

# Files Path
LOG_DIR = "E:\Log\Factory"+'\\'+str(datetime.date.today())            #Log directory
APK_ALL_NAME = "APK_all.log"                                          #Complete log
APK_ERROR_NAME = "APK_error.log"                                      #Error log
APK_BAT_DIR = "E:\\A_Document\\TCMD_APK_TEST\\apk"                    #APK script path
list_filename = [
'1-KeyPad',
'2-TouchScreenTest',
'3-ManualTouchScreenApkTest',
'4-DisplayTest',
'3.37 Camera APK - Read # Of Cameras',
'3.39.1-Gyro calibration',
# '3.39.2-OIS Hall Test',
'5.3-InternalCameraFocusTest',
'3.43.1 Front Main Camera',
'3.44.1 Rear Main Camera Blemish Test',
'3.44.2 Rear Wide&Depth Camera Blemish Test',
'3.44.3 Rear Macro Camera Blemish Test',
'5.5-InternalCameraBlemish-andRelativeUnigormityTest',
'3.46.1 Rear Main and Rear Depth Arcsoft Calibration',
# '3.46.2 Rear Main and Rear Depth Arcsoft Verification',
'3.47.1 Rear Main Camera LED Test',
'6.1-AudioCalibration',
'6.2-EarpieceSpeakerAmpliudeandDistortionTest',
'6.3-HeadsetInterface',
'7-NFC_tag-TEST',
]

# Find files
def find_files(files_path, files_list, filename):
    files = os.listdir(files_path)
    for s in files:
        s_path = os.path.join(files_path, s)
        if os.path.isdir(s_path):
            find_files(s_path, files_list,filename)
        elif os.path.isfile(s_path) and filename in s:
            result.append(s_path)
    if len(result) > 0:
        return True

# Find directory
def find_dir(dirName, topPathName = 'autotest'):
    abPath = '' #目标目录路径，默认为空
    # cp = '.' + os.path.sep #当前脚本的上层目录
    cp = APK_BAT_DIR
    if len(dirName) > 1:
        p = os.path.abspath(cp) #当前脚本的绝对路径
        yid = os.walk(p)
        for rootDir, pathList, fileList in yid:
            for path in pathList:
                if dirName == path or dirName == path.lower():
                    abPath = os.path.join(rootDir, path)
                    return (abPath + os.path.sep)
        cp = cp + '..' + os.path.sep
        if topPathName == p[p.rfind(os.path.sep)+1:]:
            #msg = u"Not find special path: '%s', please confirm the path name is correct." % dirName
            #abPath = 'not found the dir'
            return False

# Execute cmd
def exec_cmd(cmd):
    # cmd = 'cmd.exe d:/start.bat'
    p = subprocess.Popen("cmd.exe /c" + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    curline = p.stdout.readline()
    while (curline != b''):
        print(curline)
        curline = p.stdout.readline()
    p.wait()
    if p.returncode != 0: #执行失败
        print ("exec cmd error: "+cmd+"\n")
        return False

# Convert ansi file to utf-8
def ansi_to_utf8(file_path,file):
    encoding = get_encoding(file_path,file)
    if encoding != 'utf-8':
        file_name = file_path+ '\\' + file
        f= codecs.open(file_name,'r','ansi')
        ff= f.read()
        file_object= codecs.open(file_path+ '\\' + file, 'w', 'utf-8')
        file_object.write(ff)

# Get file encoding format
def get_encoding(file_path,file):
    file_name = file_path+ '\\' + file
    with open(file_name,'rb') as f:
        tmp = chardet.detect(f.read())
        return tmp['encoding']

# Read and write files
def op_file(filename,content=None):
    f = open(filename,'a+',encoding='utf-8')
    f.seek(0)
    if content:
        f.writelines(content)
        res = None
    else:
        res = f.readlines()
    f.close()
    return res

# Command
def cmd(bat,d_path,d_name):
    command = "\"%s\" > %s\\%s" % (bat,d_path,d_name)
    return command

# 遍历日志文件：
# 找出含有 error 或 Failure data received 的行和它的执行指令，按格式写入文件
def operation_log(f_file,f_path,d_file,d_path,error1,error2,obj_cmd):
    index = 0
    error = 0
    ansi_to_utf8(f_path,f_file)
    log_file = os.path.join(f_path, f_file)
    f = op_file(log_file)
    for j in f:
        index += 1
        m = re.search(error1,j,re.IGNORECASE)
        n = re.search(error2,j,re.IGNORECASE)
        if (m or n) and index > 10:
            error = 1
            break
    if error == 1:
        exec_cmd("echo ERROR Task: \"" + filename + "\" >> " + f_path + "\\" + d_file)
        exec_cmd("echo CMD: \"" + cmd(tmp_data,LOG_DIR,APK_ALL_NAME) + "\" >> " + f_path + "\\" + d_file)

# Create log directory
def mkdir(path):
    path=path.strip()
    path=path.rstrip("\\")
    isExists=os.path.exists(path) #查询目录是否存在
    if not isExists:
        os.makedirs(path) 
        print (path+' 创建成功')
        return True
    else:
        print (path+' 目录已存在')
        return False

if __name__ == '__main__':
    tmp_data = None
    retval = None
    index = 0
    if exec_cmd("adb root && adb remount") != False:
        mkdir(LOG_DIR)
        for index in range(len(list_filename)):
            result=[]
            filename = list_filename[index]
            if find_files(APK_BAT_DIR,result,filename) == True:
                tmp_data = result[0]
                print((cmd(tmp_data,LOG_DIR,APK_ALL_NAME))) #log
                exec_cmd(cmd(tmp_data,LOG_DIR,APK_ALL_NAME))
                operation_log(APK_ALL_NAME,LOG_DIR,APK_ERROR_NAME,LOG_DIR,"FAILED:","CMD returned failed","adb shell cqa_send")
            else:
                _dir = find_dir(filename)
                if _dir != (None or False):  
                    retval = find_files(_dir,result,'.bat')
                    if retval == True:
                        for i in range(len(result)):
                            tmp_data = result[i]
                            print("cd /d \""+tmp_data[:-8]+"\"" + "\n" + cmd(tmp_data,LOG_DIR,APK_ALL_NAME)) #log
                            exec_cmd("cd /d \""+tmp_data[:-8]+"\"" + "&&" + cmd(tmp_data,LOG_DIR,APK_ALL_NAME))
                            operation_log(APK_ALL_NAME,LOG_DIR,APK_ERROR_NAME,LOG_DIR,"FAILED:","CMD returned failed","adb shell cqa_send")
